package com.jingding.procurement.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Optional;

/**
 * 统一日志处理切面
 */

@Aspect
//@Component
@Order(1)
@Slf4j
public class WebLogAspect {

    @Around("@within(org.springframework.web.bind.annotation.RestController)" + "||@within(org.springframework.stereotype.Controller)")
    public Object after(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("》》》》》》》》请求接口开始");
        log.info("请求地址: {}", Optional.ofNullable(request.getRequestURL().toString()).orElse(null));
        log.info("请求方式: {}", request.getMethod());
        log.info("请求方法: {}", joinPoint.getSignature());
        log.info("请求参数: {}", Arrays.toString(joinPoint.getArgs()));
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        log.info("返回结果: {}", result == null ? "无返回结果!" : result.toString());
        log.info("执行耗时: {} ms", endTime - startTime);
        log.info("请求接口结束");
        log.info("》》》》》》》》请求接口结束");
        return result;
    }
}
